package com.easy.demo.demos.web.listener;

import com.easy.demo.demos.web.service.LeaveService;
import com.easy.demo.demos.web.vo.Leave;
import com.easy.activiti.ext.IActivitiListener;
import com.easy.activiti.ext.OnActivitiEvent;
import com.easy.activiti.ext.TaskEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhouchuang
 * @date 2024-11-12 23:21:06
 */
@OnActivitiEvent(value = "LeaveApplication2")
@Service
public class LeaveListener2 implements IActivitiListener {

    @Autowired
    private LeaveService leaveService;
    @Override
    public void processStarted(TaskEvent taskEvent){
        //改成审批中
        Leave leave = leaveService.get(taskEvent.getBusinessKey());
        leave.setStatus(Leave.Status.APPROVING.getCode());
        leave.setInstId(taskEvent.getProcessInstanceId());
        leaveService.update(leave);
    }

    @Override
    public Map<String, Object> startVariables(String businessKey) {
        Leave leave = leaveService.get(businessKey);
        return new HashMap<String,Object>(){{
            put("hr","zhouchuang");
            put("days", leave.getDays());
            put("username", leave.getUsername());
            put("reason", leave.getReason());
        }};
    }

    @OnActivitiEvent(type = OnActivitiEvent.Type.TASK_CREATED,name = "经理审批")
    public void setManager(TaskEvent taskEvent) {
        taskEvent.setAssignee("lisi");
    }

    @OnActivitiEvent(type = OnActivitiEvent.Type.TASK_CREATED,name = "CEO审批")
    public void setCEO(TaskEvent taskEvent) {
        taskEvent.setAssignee("zhangsan");
    }

    @Override
    public void created(TaskEvent taskEvent) {
        Leave leave = leaveService.get(taskEvent.getBusinessKey());
        //这个方法里面设置的变量，会体现到所有审批节点中，以下方法就是给每个节点都指定一个业务访问路径，该路径可以在审核界面的时候，审核人员看到相关的业务情况
        taskEvent.getTaskEntity().setDescription(String.format("/demo/Leave.html?username=%s&days=%s&reason=%s", leave.getUsername(), leave.getDays(), leave.getReason()));
    }
    @Override
    public void processComplete(TaskEvent taskEvent) {
        //流程走完，改成审批通过
        Leave leave = leaveService.get(taskEvent.getBusinessKey());
        leave.setStatus(Leave.Status.PASS.getCode());
        leaveService.update(leave);
    }

    @Override
    public  void reject(TaskEvent taskEvent) {
        Leave leave = leaveService.get(taskEvent.getBusinessKey());
        leave.setStatus(Leave.Status.REJECT.getCode());
        leaveService.update(leave);
    }
}
